// index.ts
import tran from "../../utils/language";
import {
    login,
    groupList,
    userList,
    userTargetInfo,
    userMobile,
} from "../../utils/api.js";
Component({
    lifetimes: {
        created() {
            // 先清空
            this.setData({
                userArrList: [],
            });
            this.getAvatarPic();
            setTimeout(() => {
                this.getMbtil();
                const userInfo = wx.getStorageSync("userInfo");
                const loginInfo = wx.getStorageSync("loginInfo");
                const hasMobile =
                    getApp().globalData.hasMobile || loginInfo.hasMobile;
                const completedStep = loginInfo.completedStep;
                this.noLoginOpenPopup();
                if (loginInfo) {
                    this.setData({
                        loginInfo: userInfo,
                        avatarPic: userInfo.avatar,
                        hasMobile,
                        beginTestShow:
                            loginInfo.completedStep == 5 ? true : false,
                        completedStep: completedStep,
                        popupParams: {
                            showPopup: true,
                            showType:
                                completedStep == 5 && hasMobile == true ? 2 : 0, // 0 注册 1 登录  2 今天想做什么
                        },
                    });
                } else {
                    // 调用登录的功能
                    // this.getLoginToken()
                    // getApp().getLogin()
                }
            }, 2000);
        },
        // attached() {
        //     getApp().getTotalUnreadCount();
        // },
    },
    pageLifetimes: {
        show() {
            console.log("show-home");
            getApp().updateTabBar(getApp().globalData.totalUnread);
            const loginInfo = wx.getStorageSync("loginInfo");
            const homeTabSel = wx.getStorageSync("homeTabSel");
            let completedStep = 0;
            if (loginInfo) {
                completedStep = loginInfo.completedStep;
            }
            // 默认回到群组
            this.setData(
                {
                    selected: homeTabSel || "Users",
                    completedStep: completedStep,
                    hasMobile: loginInfo.hasMobile,
                    userArrList: [],
                },
                () => {
                    this.getAvatarPic();
                }
            );
            if (homeTabSel == "Users") {
                this.getUserList();
            } else {
                this.getGroupList();
            }
            const completedStepFlag = wx.getStorageSync("completedStepFlag");
            this.getAvatarPic();
            if (loginInfo.completedStep == 5) {
                this.setData({
                    beginTestShow: true,
                });
            } else {
                this.setData({
                    beginTestShow: false,
                });
            }
            // 调用登录的功能
            // this.getLoginToken()
            // 判断是否是从注册账号步骤5（性格类型）哪里过来的，如果是，就再调用登录功能
            if (completedStepFlag == true) {
                // 调用登录功能
                getApp().getLogin();
                wx.removeStorageSync("completedStepFlag");
                this.getAvatarPic();
            }
            // this.getUser()
            // 获取群组列表
            // this.getGroupList()
            if (typeof this.getTabBar === "function" && this.getTabBar()) {
                this.getTabBar().setData({
                    activeKey: "home",
                });
            }
        },
        hide() {
            this.pickerSelectCancel();
        },
    },
    data: {
        _t: tran._t("home"),
        _tBase: tran._t("base"),
        overflowCss: "hidden",
        loadingFlag: false,
        selected: "Users",
        avatarPic: wx.getStorageSync("userInfo")
            ? wx.getStorageSync("userInfo").avatar
            : "",
        beginEqTestPopup: {
            showPopup: false,
            showType: 1, // 0 注册 1 登录  2 今天想做什么
        },
        popupParams: {
            showPopup: false,
            showType: 2, // 0 注册 1 登录  2 今天想做什么
        },
        filterPopupParams: {
            showDownPopup: false,
            showType: 1,
        },
        downPopupParams: {
            showDownPopup: false,
            showType: 0, // 0 注册 1 今天想做什么
        },
        registered: getApp().globalData.userId ? true : false,
        isLogin: getApp().globalData.token ? true : false,
        filterData: [
            { text: "找个搭子一起玩", key: "1", selectFlag: true },
            { text: "找个师父学点啥", key: "2", selectFlag: false },
            { text: "找个朋友聊聊天", key: "3", selectFlag: false },
            { text: "开启情商提升之旅", key: "4", selectFlag: false },
        ],
        groupArrList: [],
        filterParams: {
            interestIds: "",
            characterType: "",
            professionId: null,
            personalities: "",
            professionName: null,
            interestName: "",
            languageText: "",
            languages: null,
            genderText: "",
            gender: "",
            ageText: "",
            ageValue: "",
            minAge: null,
            maxAge: null,
            online: "all",
            currentProvinceCode: "",
            currentCityCode: "",
            currentDistrictCode: "",
            regionTextList: [],
            mbtiSwitch: false,
        },
        userArrList: [],
        userArrObj: {},
        keyword: "",
        typeBtnList: [],
        homeFriendInfo: {},
        loginInfo: {
            userId: "",
        },
        beginTestShow: false,
        completedStep: 0, // 代表没完成注册的是那一个步骤，0是代表第一个步骤，1是代表第二个步骤...以此类推，5就是代表全部完成
        hasMobile: false, // 如果为false，就说明要更新手机号
        mbtiSearch: false, // 是否性格筛选
        ageSearch: false, // 是否年龄筛选
        regionSearch: false, // 是否区域筛选
        genderSearch: false, // 是否性别筛选
        homeFriendInfoFlag: "1", // 用户类型
        mobileCode: "", // 获取用户手机号的code，拿到此code去调用后端接口,
        defaultPic: "/images/defaultPic.png",
        resetUserFlag: false,
        confirmPopup: {
            showPopup: false,
            topTitle: tran._t("base").topTitleTip,
            midText: tran._t("base").deleteUserText,
            confirmText: tran._t("base").confirmText,
            // closeText: tran._t('base').closeBtnText,
        },
        pickerParams: {
            show: false,
            pickerType: "MBTI",
            defaultValue: "",
            title: "性格类型",
            data: ["ENFP", "ENSP"],
        },
        pickerHomeAreaParams: {
            show: false,
            pickerType: "areaRegion",
            defaultValue: [""],
            data: [] as commonPickerDataType[],
        },
        commonPickerAgeParams: {
            show: false,
            pickerType: "age",
            defaultValue: "",
            data: [] as commonPickerDataType[],
        },
        commonPickerGenderParams: {
            show: false,
            pickerType: "gender",
            defaultValue: "",
            data: [] as commonPickerDataType[],
        },
        groupRegisterFlag: false, // 是否点击的是加入群组后弹出的注册框
        formData: {
            interestIds: "",
            characterType: "",
            professionId: "",
            personalities: "",
            professionName: "",
            interestName: "",
            languageText: "",
            languages: "",
            genderText: "",
            gender: "",
            ageText: "",
            minAge: 0,
            maxAge: 0,
            online: "all",
            currentProvinceCode: "",
            currentCityCode: "",
            currentDistrictCode: "",
            regionTextList: [],
            regionCodeList: [],
            ageValue: "",
        },
        regionTextList: [],
        regionCodeList: [],
        mbtiList: [
            {
                selectFlag: false,
                text: "INTP",
            },
            {
                selectFlag: false,
                text: "INTJ",
            },
            {
                selectFlag: false,
                text: "ENTJ",
            },
            {
                selectFlag: false,
                text: "ENTP",
            },
            {
                selectFlag: false,
                text: "ENFP",
            },
            {
                selectFlag: false,
                text: "INFP",
            },
            {
                selectFlag: false,
                text: "ENFJ",
            },
            {
                selectFlag: false,
                text: "INFJ",
            },
            {
                selectFlag: false,
                text: "ISTJ",
            },
            {
                selectFlag: false,
                text: "ISFJ",
            },
            {
                selectFlag: false,
                text: "ESTJ",
            },
            {
                selectFlag: false,
                text: "ESFJ",
            },
            {
                selectFlag: false,
                text: "ISTP",
            },
            {
                selectFlag: false,
                text: "ISFP",
            },
            {
                selectFlag: false,
                text: "ESTP",
            },
            {
                selectFlag: false,
                text: "ESFP",
            },
        ],
        ageList: [
            {
                selectFlag: false,
                text: "18及以下",
                value: "0-18",
            },
            {
                selectFlag: false,
                text: "18-25",
                value: "18-25",
            },
            {
                selectFlag: false,
                text: "26-32",
                value: "26-32",
            },
            {
                selectFlag: false,
                text: "33-41",
                value: "33-41",
            },
            {
                selectFlag: false,
                text: "42-55",
                value: "42-55",
            },
            {
                selectFlag: false,
                text: "55及以上",
                value: "55-200",
            },
        ],
        selectMbtiList: [
            {
                selectFlag: false,
                text: "",
                tagTypeId: "",
            },
        ],
        commonPickerGenderData: [
            {
                text: "全部",
                value: "",
                selectFlag: false,
            },
            {
                text: "女性",
                value: "2",
                selectFlag: false,
            },
            {
                text: "男性",
                value: "1",
                selectFlag: false,
            },
            {
                text: "其他",
                value: "0",
                selectFlag: false,
            },
        ],
        selectBtnList: [
            {
                selectFlag: false,
                text: "性格",
                value: "mbti",
            },
            {
                selectFlag: false,
                text: "年龄",
                value: "age",
            },
            {
                selectFlag: false,
                text: "区域",
                value: "region",
            },
            {
                selectFlag: false,
                text: "性别",
                value: "gender",
            },
        ],
        commonPickerType: "",
        needAuthFlag: true, // 为true，就是需要授权登录，为false，就是不需要授权登录，直接走注册
        mbtiSwitch: false, // 默认开启性格查询
    },
    methods: {
        // 当前页面的登录
        loginFn() {
            const that = this;
            const { selected } = this.data;
            wx.login({
                success(res1) {
                    if (res1.code) {
                        console.log(res1, 99);
                        // 调用登录的接口
                        const params = {
                            code: res1.code,
                        };
                        login(params).then((res: any) => {
                            console.log(res, "555");
                            const { header, data } = res;
                            let loginInfo = data.data;
                            let token =
                                header["Frieneed-Mini-Program-Satoken"] ||
                                header["frieneed-mini-program-satoken"];
                            let key =
                                header["Access-Control-Expose-Headers"] ||
                                header["access-control-expose-headers"]; // 用户的token放在response里面返回的
                            let obj = {
                                token,
                                key,
                                ...loginInfo,
                            };
                            wx.setStorage({
                                key: "loginInfo",
                                data: obj,
                                success() {
                                    getApp().getUserInfo();
                                    setTimeout(() => {
                                        that.getAvatarPic();
                                        console.log(selected);

                                        if (selected == "Groups") {
                                            that.getGroupList();
                                        } else {
                                            that.getUserList();
                                        }
                                    }, 1000);
                                },
                            });
                            if (obj && Object.keys(obj).length > 0) {
                                // 不等于5，就说明没注册完成
                                if (obj.completedStep != 5) {
                                    that.jumpRegisterPage();
                                }
                            }
                        });
                    } else {
                        wx.showToast({
                            title: "网络异常",
                            icon: "none",
                        });
                        return {};
                    }
                },
            });
        },
        // 筛选框开始
        homeSelectBtn(e: any) {
            const {
                pickerParams,
                pickerHomeAreaParams,
                commonPickerAgeParams,
                commonPickerGenderParams,
            } = e.detail;
            let commonPickerType = "age";
            if (pickerHomeAreaParams.show == true) {
                commonPickerType = "age";
            } else {
                commonPickerType = "gender";
            }
            this.setData({
                commonPickerType,
                pickerParams,
                pickerHomeAreaParams,
                commonPickerAgeParams,
                commonPickerGenderParams,
            });
        },
        mbtiSwitchChange(e: any) {
            const { filterParams } = this.data;
            filterParams.mbtiSwitch = e.detail;
            console.log(e);
            filterParams.mbtiSwitch = e.detail;
            this.setData({
                mbtiSwitch: e.detail,
                filterParams,
            });
        },
        // 筛选关闭弹框
        pickerSelectCancel() {
            const {
                pickerParams,
                commonPickerAgeParams,
                commonPickerGenderParams,
                pickerHomeAreaParams,
            } = this.data;
            pickerParams.show = false;
            commonPickerAgeParams.show = false;
            commonPickerGenderParams.show = false;
            pickerHomeAreaParams.show = false;
            this.setData({
                pickerParams,
                commonPickerAgeParams,
                commonPickerGenderParams,
                pickerHomeAreaParams,
            });
        },

        // 性格选择器面板确认按钮
        confirmPicker(e: any) {
            const { pickerParams } = this.data;
            pickerParams.show = false;
            if (e.detail && e.detail.length > 0) {
                // selectBtnList
            }
            this.setData(
                {
                    selectMbtiList: e.detail,
                    pickerParams,
                },
                () => {
                    this.handlePickerData();
                    this.pickerSelectCancel();
                }
            );
        },
        // 处理选择器的数据
        handlePickerData() {
            const { selectMbtiList, formData, pickerParams } = this.data;
            pickerParams.show = false;
            // 过滤出选中的几项
            let ids: any = [];
            let nameList: any = [];
            selectMbtiList.length > 0 &&
                selectMbtiList.map((item: any) => {
                    ids.push(item.tagTypeId);
                    nameList.push(item.text);
                });
            let textList: any = [];
            selectMbtiList.length > 0 &&
                selectMbtiList.map((item: any) => {
                    textList.push(item.text);
                });
            formData.personalities =
                textList.length > 0 ? textList.join(",") : "";
            this.setData({
                formData,
            });
            pickerParams.defaultValue = textList;
            this.setData(
                {
                    formData,
                    textList,
                    pickerParams,
                },
                () => {
                    // this.triggerEvent('filterSelectChange', formData)
                    this.filterSelectChange(formData);
                }
            );
        },
        getMbtil() {
            let list = getApp().globalData.mbtiList;
            const { pickerParams } = this.data;
            let mbtiList: any = [
                // {
                //   selectFlag: false,
                //   text: '全部'
                // }
            ];
            list.length > 0 &&
                list.map((item: any) => {
                    const obj = {
                        selectFlag: false,
                        text: item,
                    };
                    mbtiList.push(obj);
                });
            pickerParams.data = mbtiList;
            this.setData({
                selectList: mbtiList,
                mbtiList,
            });
        },
        /**
         * 区域选择器确认按钮
         * @param e
         */
        commonHomeAreaPickerConfirm(e: any) {
            const obj = e.detail.value;
            if (obj && Object.keys(obj).length > 0) {
                const { formData } = this.data;
                const regionCodeList: any = [
                    obj.provincesValue,
                    obj.cityValue,
                    obj.regionValue,
                ];
                const regionTextList: any = [
                    obj.provincesLabel,
                    obj.cityLabel,
                    obj.regionLabel,
                ];
                if (regionCodeList.length > 0) {
                    formData.currentProvinceCode = obj.provincesValue;
                    formData.currentCityCode = obj.cityValue;
                    formData.currentDistrictCode = obj.regionValue;
                    formData.regionTextList = regionTextList;
                    formData.regionCodeList = regionCodeList;
                }
                this.pickerSelectCancel();
                this.setData({
                    regionTextList,
                    regionCodeList,
                    formData,
                });
                // this.triggerEvent('filterSelectChange', formData)
                this.filterSelectChange(formData);
            }
        },
        /**
         * 年龄的选择器确认按钮
         * @param e
         */
        commonAgePickerConfirm(e: any) {
            const obj = e.detail.value;
            const { formData } = this.data;
            formData.ageText = obj.text;
            formData.ageValue = obj.value;
            const list = obj.value.split("-");
            formData.minAge = list[0];
            formData.maxAge = list[1];
            // 关闭弹框
            this.pickerSelectCancel();
            this.setData(
                {
                    formData,
                },
                () => {
                    this.filterSelectChange(formData);
                }
            );
        },
        /**
         * 性别的选择器确认按钮
         * @param e
         */
        commonPickerConfirm(e: any) {
            const obj = e.detail.value;
            const { formData } = this.data;
            formData.genderText = obj.text;
            formData.gender = obj.value;
            // 关闭弹框
            this.pickerSelectCancel();
            this.setData(
                {
                    formData,
                },
                () => {
                    this.filterSelectChange(formData);
                }
            );
        },
        /**
         * 重置用户筛选的条件
         */
        resetUserCondition() {
            const { selectBtnList } = this.data;
            selectBtnList.map((item) => {
                item.selectFlag = false;
            });
            this.setData({
                selectBtnList,
            });
        },
        handleMbti() {
            const { filterParams, pickerParams } = this.data;
            if (filterParams.personalities) {
                pickerParams.defaultValue = filterParams.personalities;
                this.setData({
                    pickerParams,
                });
            }
        },
        handlAge() {
            const { filterParams, commonPickerAgeParams } = this.data;
            if (filterParams.ageValue) {
                commonPickerAgeParams.defaultValue = filterParams.ageText;
            }
            this.setData({
                commonPickerAgeParams,
            });
        },
        // 处理区域回显
        handleRegion() {
            const { filterParams, pickerHomeAreaParams } = this.data;
            if (filterParams.currentProvinceCode) {
                pickerHomeAreaParams.defaultValue = [
                    filterParams.currentProvinceCode,
                    filterParams.currentCityCode,
                    filterParams.currentDistrictCode,
                ];
                this.setData({
                    pickerHomeAreaParams,
                });
            }
        },
        // 筛选框结束
        /**
         * 打开禁用账号或者删除账号的弹框
         */
        openConfirmPopup(code: any) {
            const { confirmPopup } = this.data;
            console.log(confirmPopup, code, "这这");
            confirmPopup.showPopup = true;
            if (code == 3003) {
                // 被禁用
                confirmPopup.midText = this.data._tBase["disableUserText"];
            } else {
                // 被删除
                confirmPopup.midText = this.data._tBase["deleteUserText"];
            }
            this.setData({
                confirmPopup,
                avatarPic: "",
            });
        },
        confirmFn() {
            this.closeFn();
            wx.clearStorage();
            wx.switchTab({
                url: "/pages/home/index",
            });
        },
        closeFn() {
            const { confirmPopup } = this.data;
            confirmPopup.showPopup = false;
            this.setData({
                confirmPopup,
            });
        },
        // 获取用户头像
        getAvatarPic() {
            let info = wx.getStorageSync("userInfo");
            if (info && Object.keys(info).length > 0) {
                this.setData({
                    avatarPic: info.avatar,
                });
                return false;
            } else {
                this.setData({
                    avatarPic: "",
                });
                setTimeout(() => {
                    let info = wx.getStorageSync("userInfo");
                    if (info && Object.keys(info).length > 0) {
                        this.setData({
                            avatarPic: info.avatar,
                        });
                        return false;
                    }
                }, 2500);
            }
        },
        goPartner() {
            const { filterData, popupParams, hasMobile, completedStep } =
                this.data;
            // 判断已登录注册完成
            if (hasMobile == true && completedStep == 5) {
                popupParams.showPopup = false;
                this.setData({
                    popupParams,
                });
            } else {
                this.showPopup(0);
                return false;
            }
            const list: any = filterData.filter(
                (item) => item.selectFlag == true
            );
            if (list.length > 0) {
                // 说明有选中的
                const obj = list[0];
                const { key } = obj;
                if (key == 1) {
                    // 找个搭子一起玩
                    wx.navigateTo({
                        url: "/pages/profile/findPartner/index",
                    });
                } else if (key == 2) {
                    // 找个师傅学点啥
                    wx.navigateTo({
                        url: "/pages/profile/masterStudy/index",
                    });
                } else if (key == 3) {
                    // 找个朋友聊聊天
                    wx.navigateTo({
                        url: "/pages/profile/findFriend/index",
                    });
                } else if (key == 4) {
                    // 开启情商提升之旅
                    wx.switchTab({
                        url: "/pages/metrics/index",
                    });
                }
            }
        },
        /**
         * 获取点击的用户详情
         */
        getOtherUserInfo(info: any) {
            const params = {
                targetUserId: info.userId,
            };
            userTargetInfo(params).then((res: any) => {
                const { downPopupParams } = this.data;
                downPopupParams.showDownPopup = true;
                res.homeFriendInfoFlag = "1"; // 首页过去的类型判断
                this.setData({
                    downPopupParams: downPopupParams,
                    homeFriendInfo: res,
                });
            });
        },
        /**
         * 跳转去注册
         */
        goRegister() {
            const { popupParams, needAuthFlag } = this.data;
            this.loginFn();
            this.closePopup();
            popupParams.showPopup = false;
            this.setData({
                popupParams,
            });
            const that = this;
            // if (needAuthFlag) { // 为true，就是需要授权登录
            //   // getApp().getLogin()
            //   // const info: any = this.loginFn()
            //   // console.log(info);
            //   that.jumpRegisterPage()
            // } else {
            //   that.jumpRegisterPage()
            // }
        },
        jumpRegisterPage() {
            const { popupParams } = this.data;
            popupParams.showPopup = false;
            this.setData({
                popupParams,
            });
            const loginInfo = wx.getStorageSync("loginInfo");
            let completedStep = 0;
            if (loginInfo) {
                completedStep = loginInfo.completedStep;
            }
            if (loginInfo.completedStep == 5) {
                return false;
            }
            // completedStep没完成的步骤
            if (completedStep == 0) {
                // 第一个步骤没完成
                getApp().globalData.profileFrom = "register";
                wx.navigateTo({
                    url: "/pages/profile/create-account/index?type=register",
                });
            } else if (completedStep == 1) {
                // 第二个步骤没完成
                getApp().globalData.profileFrom = "register";
                wx.navigateTo({
                    url: "/pages/profile/personalization/index?type=register",
                });
            } else if (completedStep == 2) {
                getApp().globalData.profileFrom = "register";
                wx.navigateTo({
                    url: "/pages/profile/interests-skills/index?type=register",
                });
            } else if (completedStep == 3) {
                getApp().globalData.profileFrom = "register";
                wx.navigateTo({
                    url: "/pages/profile/proficiency/index?type=register",
                });
            } else if (completedStep == 4) {
                getApp().globalData.profileFrom = "register";
                wx.navigateTo({
                    url: "/pages/profile/personality-type/index?type=register",
                });
            } else {
                getApp().globalData.profileFrom = "register";
                wx.navigateTo({
                    url: "/pages/profile/personality-type/index?type=register",
                });
            }
        },
        filterSelectChange(filterObj: any) {
            // const filterObj = e.detail
            let { filterParams } = this.data;
            filterParams.personalities = filterObj.personalities;
            filterParams.currentProvinceCode =
                filterObj.currentProvinceCode || filterObj.provincesValue;
            filterParams.currentCityCode =
                filterObj.currentCityCode || filterObj.cityValue;
            filterParams.currentDistrictCode =
                filterObj.currentDistrictCode || filterObj.regionValue;
            filterParams.minAge = filterObj.minAge || null;
            filterParams.maxAge = filterObj.maxAge || null;
            filterParams.genderText = filterObj.genderText || null;
            filterParams.gender = filterObj.gender || null;
            filterParams.regionTextList = filterObj.regionTextList;
            filterParams.ageText = filterObj.ageText;
            filterParams.ageValue = filterObj.ageValue;
            this.setData(
                {
                    filterParams,
                },
                () => {
                    this.getUserList();
                }
            );
        },
        typeFilterChange(e: any) {
            const list = e.detail;
            list.length > 0 &&
                list.map((item: any) => {
                    if (item.value == "mbti") {
                        this.setData({
                            mbtiSearch: item.selectFlag,
                        });
                    }
                    if (item.value == "age") {
                        this.setData({
                            ageSearch: item.selectFlag,
                        });
                    }
                    if (item.value == "region") {
                        this.setData({
                            regionSearch: item.selectFlag,
                        });
                    }
                    if (item.value == "gender") {
                        this.setData({
                            genderSearch: item.selectFlag,
                        });
                    }
                });
            setTimeout(() => {
                this.getUserList();
            }, 100);
        },
        keyworkChange(e: any) {
            this.setData(
                {
                    keyword: e.detail,
                },
                () => {
                    this.getUserList();
                }
            );
        },
        /**
         * 用户筛选框确认按钮
         * @param e
         */
        filterConfirm(e: any) {
            const obj = e.detail;
            this.setData(
                {
                    filterParams: obj,
                    mbtiSwitch: obj.mbtiSwitch,
                },
                () => {
                    // 关系弹框
                    this.closeFilterDownPopup();
                    // 查询用户列表
                    this.getUserList();
                }
            );
        },
        //
        /**
         * 群组列表传过来触发的事件
         * @param e
         */
        homeGroupIsLoginAndRegister(e: any) {
            const loginInfo = wx.getStorageSync("loginInfo");
            const loginFlag = this.noLoginOpenPopup();
            // 先判断是否有登录，如果有登录然后继续判断注册的弹框
            if (loginFlag) {
                // 打开去注册弹框
                if (loginInfo.completedStep == 5) {
                    this.setData({
                        groupRegisterFlag: true,
                    });
                    this.showPopup(2);
                } else {
                    this.showPopup(0);
                    this.setData({
                        groupRegisterFlag: true,
                    });
                }
            } else {
                return false;
            }
        },
        /**
         * 判断是否登录注册
         * @param e
         */
        homeGroupIsLogin(e: any) {
            const loginInfo = wx.getStorageSync("loginInfo");
            const loginFlag = this.noLoginOpenPopup();
            // 先判断是否有登录，如果有登录然后继续判断注册的弹框
            if (loginFlag) {
                // 打开去注册弹框
                if (loginInfo.completedStep == 5) {
                    this.showPopup(2);
                } else {
                    this.showPopup(0);
                }
            } else {
                return false;
            }
        },
        /**
         * 检查是否登录注册
         */
        checkRegister() {
            const userInfo = wx.getStorageSync("userInfo") || {};
            const loginInfo = wx.getStorageSync("loginInfo") || {};
            const { popupParams } = this.data;
            popupParams.showPopup = true;
            this.setData({
                hasMobile: loginInfo.hasMobile,
                completedStep: loginInfo.completedStep,
                groupRegisterFlag: false,
            });
            if (Object.keys(loginInfo).length == 0) {
                // 没有登录信息，就登录
                // popupParams.showType = 1
                // =======================================此处修改
                popupParams.showType = 0;
                this.setData({
                    popupParams,
                    needAuthFlag: true,
                });
                return false;
            }
            // hasMobile有手机号，说明是已经获取了手机号，显示登录按钮，否则显示注册按钮（获取手机号）
            popupParams.showType = loginInfo.hasMobile ? 1 : 0; // 0注册 1登录
            if (
                userInfo &&
                Object.keys(userInfo).length > 0 &&
                loginInfo.completedStep == 5
            ) {
                return true;
            } else {
                popupParams.showType = 0;
                this.setData({
                    popupParams,
                    needAuthFlag: false,
                });
                return false;
            }
        },
        /**
         * 判断如果没登录，就打开弹框
         */
        noLoginOpenPopup() {
            const loginInfo = wx.getStorageSync("loginInfo");
            if (!loginInfo) {
                const { popupParams } = this.data;
                popupParams.showPopup = true;
                // popupParams.showType = 1
                // =======================================此处修改
                popupParams.showType = 0;
                this.setData({
                    beginTestShow: false,
                    needAuthFlag: true,
                    popupParams,
                    hasMobile: loginInfo.hasMobile,
                    groupRegisterFlag: false,
                });
                return false;
            } else {
                this.setData({
                    groupRegisterFlag: false,
                    beginTestShow: loginInfo.completedStep == 5 ? true : false,
                });
                return true;
            }
        },
        /**
         * 获取用户列表方法
         */
        getUserList() {
            const loginFlag = this.noLoginOpenPopup();
            if (!loginFlag) {
                return false;
            }
            const { mbtiSwitch } = this.data;
            const {
                personalities,
                interestIds,
                professionId,
                languages,
                currentProvinceCode,
                currentCityCode,
                currentDistrictCode,
                gender,
                minAge,
                maxAge,
                online,
            } = this.data.filterParams;
            // 不选或者选择全部就传null
            let languagesValue = null;
            if (languages) {
                if (languages == "all") {
                    // 全部
                    languagesValue = null;
                } else {
                    languagesValue = [languages]; // 传数组
                }
            }
            let params = {
                pageNum: 1,
                pageSize: 100,
                keyword: this.data.keyword,
                personalities: personalities ? personalities.split(",") : null, // 性格类型,传数组
                interestIds: interestIds ? interestIds.split(",") : null, // 兴趣
                professionId: professionId, // 职业技能
                languages: languagesValue, // 语言,全部就是传null
                currentProvinceCode, // 省份code
                currentCityCode, // 市的code
                currentDistrictCode, // 区的code
                userGender: gender, // 性别
                minAge, // 年龄最小值
                maxAge: maxAge || 100, // 年龄最大值
                online: online == "all" ? null : true, // 在线状态,全部就是传null
            };
            // mbtiSwitch是否开启性格查询
            if (!mbtiSwitch) {
                params.personalities = null;
            }
            // if (!ageSearch) {
            //   params.minAge = null
            //   params.maxAge = null
            // }
            // if (!regionSearch) {
            //   params.currentProvinceCode = ''
            //   params.currentCityCode = ''
            //   params.currentDistrictCode = ''
            // }
            // if (!genderSearch) {
            //   params.userGender = null
            // }
            userList(params)
                .then((res) => {
                    if (res.code == 7000) {
                        // 未完善个人信息
                        const { popupParams } = this.data;
                        popupParams.showPopup = true;
                        popupParams.showType = 0;
                        this.setData({
                            popupParams,
                            hasMobile: false,
                            needAuthFlag: false,
                        });
                    } else if (res.code == 5001) {
                        // 未登录
                        // const { popupParams } = this.data
                        // popupParams.showPopup = true
                        // popupParams.showType = 1 // 登录
                        // this.setData({
                        //   popupParams,
                        //   hasMobile: true
                        // })
                    } else if (res.code == 3003) {
                        // 账号被封禁
                        this.openConfirmPopup(3003);
                    } else if (res.code == 3004) {
                        // 账号被注销
                        this.openConfirmPopup(3004);
                    } else {
                        // 调用成功
                        const list = res.records;
                        this.setData({
                            userArrList: list,
                            userArrObj: res.data,
                            hasMobile: true,
                        });
                    }
                })
                .catch((err: any) => {
                    console.log(err, "错误信息11");
                });
        },
        // 子组件传过来，查询群组列表
        searchGroup() {
            this.getGroupList();
        },
        /**
         * 获取群组列表方法
         */
        getGroupList() {
            let params = {};
            this.setData({
                loadingFlag: true,
            });
            groupList(params)
                .then((res) => {
                    this.setData({
                        loadingFlag: false,
                    });
                    res.length > 0 &&
                        res.map((item: any, index: any) => {
                            // 循环给每个盒子加上背景颜色
                            if (
                                item.groupType == "INTP" ||
                                item.groupType == "INTJ" ||
                                item.groupType == "ENTJ" ||
                                item.groupType == "ENTP"
                            ) {
                                // 紫色
                                item.style = "background: #dbd0e1";
                            } else if (
                                item.groupType == "ENFP" ||
                                item.groupType == "INFP" ||
                                item.groupType == "ENFJ" ||
                                item.groupType == "INFJ"
                            ) {
                                // 绿色
                                item.style = "background: #c2e4d5";
                            } else if (
                                item.groupType == "ISTJ" ||
                                item.groupType == "ISFJ" ||
                                item.groupType == "ESTJ" ||
                                item.groupType == "ESFJ"
                            ) {
                                // 蓝色
                                item.style = "background: #c6e0e9";
                            } else if (
                                item.groupType == "ISTP" ||
                                item.groupType == "ISFP" ||
                                item.groupType == "ESTP" ||
                                item.groupType == "ESFP"
                            ) {
                                // 黄色
                                item.style = "background: #f7e7c4";
                            } else if (item.groupType == "WEEKLY_HOT") {
                                // 每周热榜
                                item.style =
                                    "background: linear-gradient(135deg, #FFF0E6 0%, #DAFFF3 100%)";
                            } else if (item.groupType == "TRAINING_CAMP") {
                                // 情商
                                item.style = "background: #FFF0E6";
                            }
                            item.imgIcon = `/images/${item.groupType}.png`;
                        });
                    setTimeout(() => {
                        this.setData({
                            groupArrList: res,
                        });
                    }, 200);
                })
                .catch((err: any) => {
                    this.setData({
                        loadingFlag: false,
                    });
                });
        },
        closeFriendInfoPopup() {
            const { downPopupParams } = this.data;
            downPopupParams.showDownPopup = false;
            this.setData({
                downPopupParams,
            });
        },
        getUser() {
            const { popupParams } = this.data;
            let loginInfo = {};
            // 从缓存中获取用户登录信息
            const that = this;
            wx.getStorage({
                key: "loginInfo",
                success(res) {
                    loginInfo = res;
                },
            });
            // 判断用户是否登录，未登录打开提示框
            if (Object.keys(loginInfo).length <= 0) {
                // 未登录
                popupParams.showPopup = true;
                popupParams.showType = 0;
                that.setData({
                    popupParams,
                    needAuthFlag: true,
                });
            }
        },
        /**
         * 点击筛选的icon,弹出筛选弹框
         */
        filterShowPopup() {
            const { filterPopupParams } = this.data;
            filterPopupParams.showDownPopup = true;
            this.setData({
                filterPopupParams,
            });
        },
        // 事件处理函数
        onClickoverlay() {
            console.log("onClickoverlay");
        },
        showPopup(type: number) {
            const { filterData } = this.data;
            // 初始化，每一次都默认初始值
            filterData.length > 0 &&
                filterData.map((item: any, index: any) => {
                    if (index === 0) {
                        item.selectFlag = true;
                    } else {
                        item.selectFlag = false;
                    }
                });
            this.setData({
                popupParams: { showPopup: true, showType: type },
                filterData,
            });
        },
        closePopup() {
            this.setData({ popupParams: { showPopup: false, showType: 1 } });
        },
        closeBeginEqPopup() {
            this.setData({
                beginEqTestPopup: { showPopup: false, showType: 1 },
            });
        },
        toEqTap() {
            wx.navigateTo({
                url: "/pages/profile/eqTestQuestion/index",
            });
            this.onClosePopup();
        },
        beginEqTap() {
            const flag = this.checkRegister();
            if (!flag) {
                return false;
            }
            this.setData({
                beginEqTestPopup: { showPopup: true, showType: 1 },
            });
            // this.setData({ beginEqTestPopup: { showPopup: true, showType: 1 } })
        },
        talkLaterTap() {
            this.setData({
                beginTestShow: false,
            });
        },
        onClosePopup() {
            const { beginEqTestPopup } = this.data;
            beginEqTestPopup.showPopup = false;
            this.setData({
                beginEqTestPopup,
            });
            const customPopup = this.selectComponent("#custom-popup");
            customPopup && customPopup.hidePopup();
        },
        closeFilterDownPopup() {
            const { filterPopupParams } = this.data;
            filterPopupParams.showDownPopup = false;
            this.setData({ filterPopupParams: filterPopupParams });
        },
        closeDownPopup() {
            const downPopup = this.selectComponent("#down-popup");
            const { downPopupParams } = this.data;
            downPopupParams.showDownPopup = false;
            this.setData({ downPopupParams: downPopupParams });
            downPopup && downPopup.hidePopup();
        },
        onSelect(event: any) {
            const value = event.currentTarget.dataset.value;
            this.setData({ selected: value });
            wx.setStorage({
                key: "homeTabSel",
                data: this.data.selected,
            });
            if (value == "Users") {
                // const flag = this.checkRegister()
                // if (!flag) {
                //   return false
                // }
                this.setData(
                    {
                        userArrList: [],
                    },
                    () => {
                        this.resetFilterFn();
                        this.getUserList();
                    }
                );
            } else {
                this.resetFilterFn();
                this.getGroupList();
            }
        },
        // 重置弹框
        resetFilterFn() {
            let { filterParams } = this.data;
            filterParams = {
                interestIds: "",
                characterType: "",
                professionId: null,
                personalities: "",
                professionName: null,
                interestName: "",
                languageText: "",
                languages: null,
                genderText: "",
                gender: "",
                ageText: "",
                ageValue: "",
                minAge: null,
                maxAge: null,
                online: "all",
                currentProvinceCode: "",
                currentCityCode: "",
                currentDistrictCode: "",
                regionTextList: [],
                mbtiSwitch: true,
            };
            this.setData({
                resetUserFlag: false,
                filterParams,
            });
        },
        toProfile() {
            const flag = this.checkRegister();
            if (!flag) {
                return false;
            }
            if (flag) {
                // 已登录并注册完善
                wx.navigateTo({
                    url: "/pages/profile/info/index",
                });
            }
        },
        /**
         * 重置用户筛选的条件
         */
        resetUserCondition() {},
        todayDoWhat() {
            // const flag = this.checkRegister()
            // if (!flag) {
            //   return false
            // }
            // this.showPopup(2)
            // const flag = this.checkRegister()
            // if (!flag) {
            //   return false
            // }
            // this.showPopup(2)
            this.homeGroupIsLogin("");
        },
        toSelectPage(e: any) {
            const currentIndex = e.target.dataset.index;
            const { filterData } = this.data;
            filterData.length > 0 &&
                filterData.map((item: any, index: any) => {
                    if (index === currentIndex) {
                        // item.selectFlag = !item.selectFlag
                        item.selectFlag = true;
                    } else {
                        item.selectFlag = false;
                    }
                });
            // 判断是否注册
            this.isRegister();
            this.setData({
                filterData,
            });
        },
        isRegister() {
            // 不能从this.data里面拿，因为有可能不是最新的
            const loginInfo = wx.getStorageSync("loginInfo");
            const { hasMobile, completedStep } = loginInfo;
            // 判断已登录注册完成
            if (hasMobile == true && completedStep == 5) {
                return true;
            } else {
                this.showPopup(0);
                return false;
            }
        },
        handleUser(e: any) {
            // 获取子组件传过来的数据
            const info = e.detail;
            this.getOtherUserInfo(info);
        },
        /**
         * 点击登录按钮
         */
        getLoginBtn() {
            const loginInfo = wx.getStorageSync("loginInfo");
            if (loginInfo) {
                this.goRegister();
            } else {
                this.getLoginToken(3);
            }
        },
        /**
         * 拿到token
         */
        getLoginToken(getMobileFlag: any) {
            const that = this;
            wx.login({
                success(res1) {
                    if (res1.code) {
                        // 调用登录的接口
                        const params = {
                            code: res1.code,
                        };
                        login(params).then((res: any) => {
                            const { header, data } = res;
                            let loginInfo = data.data;
                            that.openShowLoginPopup(data);
                            let token =
                                header["Frieneed-Mini-Program-Satoken"] ||
                                header["frieneed-mini-program-satoken"];
                            let key =
                                header["Access-Control-Expose-Headers"] ||
                                header["access-control-expose-headers"]; // 用户的token放在response里面返回的
                            let obj = {
                                token,
                                key,
                                ...loginInfo,
                            };
                            that.setData({
                                completedStep: obj.completedStep,
                                hasMobile: loginInfo.hasMobile,
                            });
                            wx.setStorage({
                                key: "loginInfo",
                                data: obj,
                                success() {
                                    // 调用获取个人信息的接口
                                    getApp().getUserInfo();
                                    that.getGroupList();
                                    that.getUserList();
                                    if (getMobileFlag == 2) {
                                        // 获取用户手机号
                                        that.getMobile();
                                    } else if (getMobileFlag == 3) {
                                        // 获取用户列表
                                        that.getUserList();
                                    }
                                    // 获取用户头像
                                    setTimeout(() => {
                                        that.getAvatarPic();
                                    }, 1500);
                                },
                            });
                        });
                    } else {
                        wx.showToast({
                            title: "网络异常",
                            icon: "none",
                        });
                    }
                },
            });
        },
        openShowLoginPopup(obj: any) {
            const { popupParams } = this.data;
            popupParams.showPopup = false;
            // popupParams.showType = obj.hasMobile == true && obj.completedStep == 5 ? 2 : 0 // 0 注册 1 登录  2 今天想做什么
            // 关闭弹框
            this.setData({ popupParams, completedStep: obj.completedStep });
        },
        getPhoneNumber(e: baseEvent) {
            const that = this;
            if (e.detail.errMsg === "getPhoneNumber:ok") {
                // 获取到加密数据
                const { encryptedData, iv, code } = e.detail;
                that.setData(
                    {
                        mobileCode: code,
                    },
                    () => {
                        that.getLoginToken(2);
                    }
                );
                // 调用登录的接口
                // that.getMobile()
            } else {
                console.warn("用户拒绝授权");
            }
        },
        /**
         * 调用更新手机号的接口
         */
        getMobile() {
            const that = this;
            const params = {
                code: this.data.mobileCode,
            };
            userMobile(params).then((res: any) => {
                const { popupParams } = that.data;
                popupParams.showPopup = false;
                popupParams.showType = 2;
                // 关闭弹框
                that.setData({ popupParams, hasMobile: true });
                let loginInfo = wx.getStorageSync("loginInfo");
                loginInfo.hasMobile = true;
                wx.setStorageSync("loginInfo", loginInfo);
                getApp().getUserInfo();
                // that.goRegister()
            });
        },
    },
});
